import io

import minio
from config import envConfig

MINIO_CONFIG = {
    "endpoint": envConfig.MINIO_ENDPOINT,
    "access_key": envConfig.ACCESS_KEY,
    "secret_key": envConfig.SECRET_KEY,
    "secure": False,
}


class MinIOHandler:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = object.__new__(cls)
        return cls._instance

    _minio_client = minio.Minio(**MINIO_CONFIG)

    # 实例化minio
    @classmethod
    def get_conn(cls):
        conn = cls._minio_client
        return conn

    @classmethod
    def check_file_existence(cls, bucket_name, object_name):
        try:

            return cls._minio_client.stat_object(bucket_name, object_name).size > 0
        except minio.error.S3Error as e:
            if e.code == "NoSuchKey":
                return False
            else:
                print("发生错误:", e)
                return False

    @classmethod
    def create_directory(cls, bucket_name, directory_path):
        try:
            if not directory_path.endswith('/'):
                directory_path += '/'
            cls._minio_client.put_object(
                bucket_name=bucket_name,
                object_name=directory_path,
                data=io.BytesIO(b''),
                length=0
            )
            print("MINIO目录创建成功")
            return True
        except minio.error.S3Error as e:
            print("发生错误:", e)
            return False


minio_client = MinIOHandler.get_conn()


